import { MiddlewareConsumer, Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { Logger } from '@nestjs/common/services/logger.service';
import { UserModule } from './modules/user/user.module';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule, ConfigService } from 'nestjs-config';
import * as path from 'path';
import { RoleModule } from './modules/role/role.module';
import { PostsModule } from './modules/posts/posts.module';
import { LogMiddleware } from './middlewares/log.middleware';
import { AuthMiddleware } from './middlewares/auth.middleware';
import { ToolsModule } from './modules/tools/tools.module';
import { RedisUtilsModule } from './modules/redis-utils/redis-utils.module';

console.log('__dirname',__dirname);
@Module({
  imports: [
    // 配置加载配置文件
    ConfigModule.load(path.resolve(__dirname, 'config', '**/!(*.d).{ts,js}'), {
      modifyConfigName: name => name.replace('.config', ''),
    }),
    // mysql的连接
    TypeOrmModule.forRootAsync({
      useFactory: async (config: ConfigService) => ({
        type: config.get('database.type'),
        host: config.get('database.host'),
        port: config.get('database.port'),
        username: config.get('database.username'),
        password: config.get('database.password'),
        database: config.get('database.database'),
        entities: [__dirname + '/**/*.entity{.ts,.js}'],
        logging: config.get('database.logging'),
      }),
      inject: [ConfigService],
    }),
    UserModule,
    RoleModule,
    PostsModule,
    ToolsModule,
    RedisUtilsModule
  ], // 依赖外面的模块(可以是自己创建的比如userModule，或者是官方提供的比如typeorm, graphql,或者第三方的)
  controllers: [AppController], // 该模块所用到的控制器
  providers: [
    {
      provide: 'LOG',
      useClass: Logger,
    },
    {
      provide: 'APP_SERVICE',
      useFactory: (logger) => {
        logger.log('使用工厂方式');
        return '工厂方法返回';
      },
      inject: ['LOG'], // 注入的顺序就是useFactory函数的顺序
    },
    {
      provide: 'IS_DEV',
      useValue: { isDev: true },
    },
  ],
  exports: [], // 别的模块要使用该模块中的某几个方法，就要在这里对外暴漏
})
export class AppModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(LogMiddleware)
      .forRoutes('user');
  }
}
